﻿using System;
using System.Collections.Generic;
using System.IO;

namespace TfsWrapper
{
    internal class TfsRemotingWrapperDecorator : MarshalByRefObject, ITfsRemotingWrapper
    {
        private readonly TfsWrapper inner;

        public TfsRemotingWrapperDecorator()
        {
            inner = new TfsWrapper();
            Remoting.Server.OnExit += OnServerExit;
        }

        public RemoteResult Execute(IEnumerable<string> args)
        {
            using (Remoting.Server.Auditing)
            {
                var @out = new StringWriter();
                
                try
                {
                    inner.Execute(@out, args);

                    return new RemoteResult { Out = @out.ToString() };
                }
                catch
                {
                    Remoting.Server.Exit();
                    throw;
                }
            }
        }

        private void OnServerExit()
        {
            inner.Dispose();
        }
    }
}